package controller

import (
	"test/gincircl/common"
	"test/gincircl/dilithium"

	"github.com/cloudflare/circl/sign"
	"github.com/gin-gonic/gin"
)

func DilithiumGenKeyPair(c *gin.Context) {
	common.Logger.Info(c.Request.URL.Path)
	var params common.DilithiumGen
	err := c.ShouldBindJSON(&params)
	if err != nil {
		common.Logger.Error("解析参数错误:" + err.Error())
		common.FailWithMessage("解析参数错误", c)
		return
	}
	dilithium, err := dilithium.NewDilithiumr(params.Type)
	if err != nil {
		common.Logger.Error("NewDilithiumr参数错误:" + err.Error())
		common.FailWithDetailed(err.Error(), "参数错误", c)
		return
	}
	pk, prik, err := dilithium.GenerateKey()
	if err != nil {
		common.Logger.Error("生成密钥对失败:" + err.Error())
		common.FailWithDetailed(err.Error(), "生成密钥对失败", c)
		return
	}
	common.OkWithData(map[string]interface{}{
		"PublicKey":  pk,
		"PrivateKey": prik,
	}, c)

}
func DilithiumSign(c *gin.Context) {
	common.Logger.Info(c.Request.URL.Path)
	var params common.DilithiumSign
	err := c.ShouldBindJSON(&params)
	if err != nil {
		common.Logger.Error("生成密钥对失败:" + err.Error())
		common.FailWithMessage("解析参数错误", c)
		return
	}
	dilithium, err := dilithium.NewDilithiumr(params.Type)
	if err != nil {
		common.Logger.Error("生成密钥对失败:" + err.Error())
		common.FailWithDetailed(err.Error(), "参数错误", c)
		return
	}
	var opts *sign.SignatureOpts
	if params.Opts != "" {
		opts = &sign.SignatureOpts{
			Context: params.Opts,
		}
	}
	signText, err := dilithium.Sign(params.PrivateKey, params.Message, opts)
	if err != nil {
		common.Logger.Error("私钥签名失败:" + err.Error())
		common.FailWithDetailed(err.Error(), "私钥签名失败", c)
		return
	}
	common.OkWithData(map[string]interface{}{
		"signature": signText,
	}, c)

}
func DilithiumVerify(c *gin.Context) {
	common.Logger.Info(c.Request.URL.Path)
	var params common.DilithiumVerify
	err := c.ShouldBindJSON(&params)
	if err != nil {
		common.Logger.Error("解析参数错误:" + err.Error())
		common.FailWithMessage("解析参数错误", c)
		return
	}
	dilithium, err := dilithium.NewDilithiumr(params.Type)
	if err != nil {
		common.Logger.Error("NewDilithiumr参数错误:" + err.Error())
		common.FailWithDetailed(err.Error(), "参数错误", c)
		return
	}
	var opts *sign.SignatureOpts
	if params.Opts != "" {
		opts = &sign.SignatureOpts{
			Context: params.Opts,
		}
	}
	match, err := dilithium.Verify(params.PublicKey, params.Message, params.Signature, opts)
	if err != nil {
		common.Logger.Error("Verify公钥验签失败:" + err.Error())
		common.FailWithDetailed(err.Error(), "公钥验签失败", c)
		return
	}
	common.OkWithData(map[string]interface{}{
		"match": match,
	}, c)
}
